package com.zch.utils.snowflake;

public class UUIDGenerator {
    private static volatile IdWorker idWorker;
    private static final ResourceLock RESOURCE_LOCK = new ResourceLock();

    /**
     * generate UUID using snowflake algorithm
     *对外提供的生成唯一id 方法 字符串的长度在[16，19]范围内
     * @return UUID
     */
    public static long generateUUID() {
        if (idWorker == null) {
            try (ResourceLock ignored = RESOURCE_LOCK.obtain()) {
                if (idWorker == null) {
                    init(null);
                }
            }
        }
        return idWorker.nextId();
    }

    /**
     * init IdWorker
     *
     * @param serverNode the server node id, consider as machine id in snowflake
     */
    public static void init(Long serverNode) {
        idWorker = new IdWorker(serverNode);
    }
}
